package com.mao.crowd.mvc.controller;

import com.github.pagehelper.PageInfo;
import com.mao.crowd.service.api.RoleService;
import com.mao.crowd.util.ResultEntity;
import entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


/**
 * @author maomeng
 * @create 2021-06-01- 15:15
 */
@Controller
public class RoleController {

    @Autowired
    private RoleService roleService;

    /**
     * 调用service获取分页数据，返回 ResultEntity<PageInfo<Role>>
     * @param pageNum 起始页
     * @param pageSize 一页多少条数据
     * @param keyword 关键词
     * @return ResultEntity：之前定义的，统一返回格式的工具类
     */

    @PreAuthorize("hasRole('部长') or hasRole('超级管理员')")
    @ResponseBody
    @RequestMapping("/role/get/page/info.json")
    public ResultEntity<PageInfo<Role>> getPageInfo(
            @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
            @RequestParam(value = "keyword",defaultValue = "") String keyword
    ){
        PageInfo<Role> pageInfo;
        try {
//            调用service对象获取pageInfo
            pageInfo = roleService.getPageInfo(pageNum, pageSize, keyword);
//            封装进ResultEntity返回
            return ResultEntity.successWithData(pageInfo);
        }catch (Exception e){
            return ResultEntity.failed(e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping("/role/save.json")
    public ResultEntity<String> saveRole(Role role){
        roleService.saveRole(role);
        return ResultEntity.successWithOutData();
    }

    @ResponseBody
    @RequestMapping("/role/update.json")
    public ResultEntity<String> updateRole(Role role){
        roleService.updateRole(role);
        return ResultEntity.successWithOutData();
    }

    @ResponseBody
    @RequestMapping("/role/remove/by/role/id/array.json")
    public ResultEntity<String> removeByRoleIdArray(@RequestBody List<Integer> roleList){
        roleService.removeRole(roleList);
        return ResultEntity.successWithOutData();
    }
}
